package rocky.freemanagementsystemserver.handler

import org.springframework.core.MethodParameter
import org.springframework.http.MediaType
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.server.ServerHttpRequest
import org.springframework.http.server.ServerHttpResponse
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice
import rocky.freemanagementsystemserver.bean.CommomResult
import rocky.freemanagementsystemserver.bean.CommonException
import rocky.freemanagementsystemserver.bean.ErrorCode


@ControllerAdvice
class GlobalResponseHandler : ResponseBodyAdvice<Object> {
    override fun supports(returnType: MethodParameter, converterType: Class<out HttpMessageConverter<*>>): Boolean {
        var typeName = returnType.parameterType.name;
        return typeName == "rocky.freemanagementsystemserver.bean.CommomResult"
    }

    override fun beforeBodyWrite(
        body: Object?,
        returnType: MethodParameter,
        selectedContentType: MediaType,
        selectedConverterType: Class<out HttpMessageConverter<*>>,
        request: ServerHttpRequest,
        response: ServerHttpResponse
    ): Object {
        return if (body is CommomResult<*>) {
            body;
        } else {
            CommomResult<Object?>().success(body) as Object;
        }

    }

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = [Exception::class])
    fun errorHandler(ex: Exception): Object {
        val result = CommomResult<String>();
        if (ex is CommonException) {
            result.code = ex.code.value;
            result.success = false;
            result.message = ex.message;
        } else {
            return ex.message as Object;
        }
        return result as Object;
    }
}